/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-06-30 16:42:36
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-08-28 17:51:40
 * @FilePath: \keep_motion_api\models\role.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const xlsx = require('xlsx'); 
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 字典类型模型
const dictTypeSchema = new Schema({
  name: { type: String, required: true },
  code: { type: String, required: true, unique: true },
  description: String
});

// 查询字典类型
dictTypeSchema.statics.getDictType = async function (name = '', code = '', description = '', offset = 0, limit = 10) {
  try {
    const query = {};
    if (name) {
      const escapedName = escapeRegex(name);
      query.name = { $regex: escapedName, $options: 'i' };
    }
    if (code) {
      const escapedCode = escapeRegex(code);
      query.code = { $regex: escapedCode, $options: 'i' };
    }
    if (description) {
      const escapedDescription = escapeRegex(description);
      query.description = { $regex: escapedDescription, $options: 'i' };
    }
    // 先统计符合条件的记录总数
    const total = await this.countDocuments(query);
    // 再进行分页查询
    const rows = await this.find(query)
      .skip(Number(offset))
      .limit(Number(limit));

    return { rows, total };
  } catch (error) {
    throw error;
  }
}
// 创建字典类型
dictTypeSchema.statics.createDictType = async function (name, code, description) {
  try {
    const dictType = await this.create({ name, code, description });
    return dictType;
  } catch (error) {
    throw error;
  }
}
// 修改字典类型
dictTypeSchema.statics.updateDictType = async function (id, name, code, description) {
  try {
    const dictType = await this.findByIdAndUpdate(id, { name, code, description });
    return dictType;
  } catch (error) {
    throw error;
  }
}
// 删除字典类型
dictTypeSchema.statics.deleteDictType = async function (id) {
  try {
    const dictType = await this.findByIdAndDelete(id);
    return dictType;
  } catch (error) {
    throw error;
  }
}

// excal批量导入
dictTypeSchema.statics.importDictType = async function (file) {
  try {
    const workbook = xlsx.readFile(file);
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];
    const data = xlsx.utils.sheet_to_json(sheet);
    const dictTypes = await this.create(data);
    return dictTypes;
  } catch (error) {
    throw error;
  }
}

// excal 导出
dictTypeSchema.statics.exportDictType = async function (name = '', code = '', description = '') {
  try {
    const query = {};
    if (name) {
      const escapedName = escapeRegex(name);
      query.name = { $regex: escapedName, $options: 'i' };
    }
    if (code) {
      const escapedCode = escapeRegex(code);
      query.code = { $regex: escapedCode, $options: 'i' };
    }
    if (description) {
      const escapedDescription = escapeRegex(description);
      query.description = { $regex: escapedDescription, $options: 'i' };
    }
    const dictTypes = await this.find(query);
    const headerConfig = [
      { key: 'name', header: '字典名称' },
      { key: 'code', header: '字典编码' },
      { key: 'description', header: '描述' },
    ];
    const worksheet = xlsx.utils.json_to_sheet(
      dictTypes.map(item => headerConfig.reduce((obj, { key }) => {
        obj[key] = item[key];
        return obj;
      }, {})),
      // 指定表头顺序及名称
      { header: headerConfig.map(h => h.key) }
    );
    headerConfig.forEach(({ key, header }, index) => {
      const cellAddress = xlsx.utils.encode_cell({ r: 0, c: index }); // 第1行（0-based索引）
      worksheet[cellAddress].v = header; // 将英文键名替换为中文表头
    });
    const workbook = xlsx.utils.book_new();
    xlsx.utils.book_append_sheet(workbook, worksheet, 'DictType');
    const buffer = xlsx.write(workbook, {
      bookType: 'xlsx',
      type: 'buffer', // 返回Buffer对象
      cellStyles: true // 可选：保留单元格样式
    });
    return {buffer, filename: '字典类型.xlsx'};
  } catch (error) {
    throw error;
  }
}


module.exports = mongoose.model('DictType', dictTypeSchema);
